/**
 * @Author       : Hejh(3010733382@qq.com)
 * @Version      : V1.0
 * @Date         : 2024-01-14 17:39:31
 * @Description  : 用户激活码接口控制器
 */
const Mysequelize = require('@/models')
const R = require('@/models/Response')
const { UserActiveExam, ActiveCode, Exam, User } = require('@/models/model')
const { ERROR_USER_CODE } = require('@/constants/errorCode')
const { generatId } = require('@/utils/idUtil')
const { delModel, sortModel } = require('@/utils/controllerCommon')

/**
 * 列表查询用户激活码接口
 * @param {*} ctx
 * @returns
 */
module.exports.listUserActiveExam = async (ctx) => {
  const { userId, examId, activeCodeId } = ctx.query
  const whereCondition = {}
  if (userId !== undefined) {
    whereCondition.userId = userId
  }
  if (examId !== undefined) {
    whereCondition.examId = examId
  }
  if (activeCodeId !== undefined) {
    whereCondition.activeCodeId = activeCodeId
  }
  const orderCondition = [['createTime', 'desc']]

  const { page, pageSize } = ctx.query
  const start = (page - 1) * pageSize
  const { rows, count } = await UserActiveExam.findAndCountAll({
    where: whereCondition,
    include: [
      {
        model: ActiveCode
      },
      {
        model: Exam
      },
      {
        model: User
      }
    ],
    offset: +start,
    limit: +pageSize,
    order: orderCondition,
    distinct: true
  })

  ctx.body = R.success({
    page,
    pageSize,
    total: count,
    pages: Math.ceil(count / pageSize),
    items: rows
  })
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 用户使用激活码激活考试接口
 * @param {*} ctx
 */
module.exports.createUserActiveExam = async (ctx) => {
  const { activeCodeId, examId, activeCode, userId } = ctx.request.newBody
  const t = await Mysequelize.transaction()
  const nextId = generatId()
  const sort = await UserActiveExam.max('sort')

  let createObj = {
    id: nextId,
    userId: userId || ctx.user.id,
    examId,
    activeCodeId,
    sort: sort + 1,
    deadline: 100n,
    activeCode,
    createUser: ctx.user.id,
    updateUser: ctx.user.id
  }

  try {
    // 到这里可以进行用户激活码的添加了,排序字段默认是最大值
    const userActiveExam = await UserActiveExam.create(createObj, {
      transaction: t
    })
    await t.commit()
    ctx.body = R.success()
  } catch (error) {
    console.log(error, 'xxx')

    await t.rollback()
    ctx.body = R.error(ERROR_USER_CODE.USER_ACTIVE_EXAM_CREATE_ERROR)
  }
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 批量删除用户激活码接口
 * @param {*} ctx
 */
module.exports.delUserActiveExams = async (ctx) => {
  await delModel(
    UserActiveExam,
    ERROR_USER_CODE.USER_ACTIVE_EXAM_DEL_ERROR,
    'userActiveExamIds'
  )(ctx)
}

/**
 * @author: Hejh(3010733382@qq.com)
 * @description: 用户激活码排序接口
 * @param {*} ctx
 */
module.exports.sortUserActiveExams = async (ctx) => {
  // 传递的用户激活码ID顺序即为排序顺序，取出这些ID对应的sort，sort从小到大排序后，依次赋值
  await sortModel(
    UserActiveExam,
    ERROR_USER_CODE.USER_ACTIVE_EXAM_SORT_ERROR,
    'userActiveExamIds'
  )(ctx)
}
